<?php
namespace app\applet\controller;

use app\applet\model\Setting as SettingModel;
use think\facade\View;
use think\facade\Cache;
use hema\alipay\Driver;
use Endroid\QrCode\QrCode as CodeMode;
use Endroid\QrCode\Writer\PngWriter;
/**
 * 支付宝小程序
 */
class Alipay extends Controller
{
    /**
     * 参数设置
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            $model = SettingModel::getItem('alipay',$this->applet_id);
            $url = '';
            if(empty($model['app_auth_token'])){
                $isv = SettingModel::getItem('alipayopen');
                //PC 端授权参数
                $bizDataObj  = [
                    'platformCode' => 'O',
                    'taskType' => 'INTERFACE_AUTH',
                    'agentOpParam' => [
                        'redirectUri' => urlencode($isv['redirect_uri']),
                        'appTypes' => ["MOBILEAPP","WEBAPP","PUBLICAPP","TINYAPP","BASEAPP"],
                        'isvAppId' => (string)$isv['app_id'],
                        'state' => (string)$this->applet_id
                    ]
                ];
                $qrcode = 'alipays://platformapi/startapp?appId=2021003130652097&page=pages%2Fauthorize%2Findex%3FbizData%3D';
                $qrcode .= urlencode(hema_json($bizDataObj));
                if(!file_exists('./temp')){
                    mkdir('./temp',0777,true);
                }
                //生成二维码
                $writer = new PngWriter();
                $code = CodeMode::create($qrcode)->setSize(500);
                $result = $writer->write($code);
                $url = '/temp/alipay_auth_qrcode_' . $this->applet_id . '.png';
                $result->saveToFile('./' . $url);
            }else{
                //查询小程序基础信息
                $alipay = new Driver($this->applet_id);
                if($result = $alipay->openMiniBaseinfoQuery()){
                    $model['applet'] = $result;
                }
            }
            return View::fetch('index', compact('model','url'));
        }
        //修改小程序信息
        $data = $this->postData('data');
        //是否修改小程序头像
        if(isset($data['app_logo']) and !empty($data['app_logo'])){
            $logo = fopen($data['app_logo'], 'rb'); // 以二进制方式打开图片文件
            $binary = fread($logo, filesize($data['app_logo'])); // 读取图片二进制数据
            $data['app_logo'] = unpack('C*', $binary); // 将二进制数据转换成byte数组
        }
        $alipay = new Driver($this->applet_id);
        if(!$alipay->openMiniBaseinfoModify($data)){
			return $this->renderError($alipay->getError());
		}
		return $this->renderSuccess('操作成功',url('alipay/index'));
    }
    
    /**
     * 授权状态检测
     */
    public function auth()
    {
        if(!Cache::pull('alipay_auth_' . $this->applet_id)){
            return $this->renderSuccess('授权完成');
        }
        return $this->renderError('授权中');
    }
}